package com.zzw.springboot.controller;

import com.zzw.springboot.bean.SysMenu;
import com.zzw.springboot.service.SysMenuService;
import com.zzw.springboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/sysMenu")
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;

    @GetMapping("/listRootMenu")
    public Result listRootMenu() {
        List<SysMenu> sysMenuList = sysMenuService.listRootMenu();
        return Result.success(sysMenuList);
    }

    /**
     * 根据父节点ID获取子节点菜单
     */
    @GetMapping("/listChildMenu/{parentId}")
    public Result listChildMenu(@PathVariable("parentId") Integer parentId) {
        List<SysMenu> sysMenuList = sysMenuService.listChildMenu(parentId);
        return Result.success(sysMenuList);
    }

    /**
     * 根据父节点ID获取子节点
     */
    @GetMapping("/listChildNode/{parentId}")
    public Result listChildNode(@PathVariable("parentId") Integer parentId) {
        List<SysMenu> sysMenuList = sysMenuService.listChildNode(parentId);
        return Result.success(sysMenuList);
    }

    @GetMapping("getInfo/{id}")
    public Result getInfo(@PathVariable("id") Integer id) {
        SysMenu sysMenu = sysMenuService.getById(id);
        return Result.success(sysMenu);
    }

    @PostMapping("/add")
    public Result add(@RequestBody SysMenu sysMenu) {
        boolean save = sysMenuService.save(sysMenu);
        if (save) {
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }

    @PutMapping("/update")
    public Result update(@RequestBody SysMenu sysMenu) {
        boolean update = sysMenuService.updateById(sysMenu);
        if (update) {
            return Result.success("修改成功");
        }
        return Result.error("修改失败");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        boolean delete = sysMenuService.removeById(id);
        if (delete) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }

    /**
     * 获取路由信息
     */
    @GetMapping("/getRouters")
    public Result getRouters() {
        // 获取所有菜单
        List<SysMenu> allMenus = new ArrayList<>();

        // 先获取根菜单
        List<SysMenu> rootMenus = sysMenuService.listRootMenu();
        allMenus.addAll(rootMenus);

        // 递归获取所有子菜单
        for (SysMenu rootMenu : rootMenus) {
            getChildMenus(rootMenu.getId(), allMenus);
        }

        // 只保留菜单和目录类型（不包括按钮）
        List<SysMenu> routerMenus = allMenus.stream()
                .filter(menu -> "M".equals(menu.getMenuType()) || "C".equals(menu.getMenuType()))
                .filter(menu -> menu.getStatus() == 1) // 只获取状态正常的
                .filter(menu -> menu.getIsHidden() == 0) // 只获取显示的菜单
                .collect(Collectors.toList());

        // 构建路由树结构
        List<Map<String, Object>> routerList = buildRouterTree(routerMenus);

        return Result.success(routerList);
    }

    /**
     * 递归获取子菜单
     */
    private void getChildMenus(Integer parentId, List<SysMenu> menuList) {
        List<SysMenu> childMenus = sysMenuService.listChildMenu(parentId);
        if (childMenus != null && !childMenus.isEmpty()) {
            menuList.addAll(childMenus);
            // 递归获取下一级
            for (SysMenu childMenu : childMenus) {
                getChildMenus(childMenu.getId(), menuList);
            }
        }
    }

    /**
     * 构建前端路由所需要的格式
     */
    private List<Map<String, Object>> buildRouterTree(List<SysMenu> menus) {
        List<Map<String, Object>> routers = new ArrayList<>();

        // 按父节点分组
        Map<Integer, List<SysMenu>> parentMap = new HashMap<>();
        for (SysMenu menu : menus) {
            Integer parentId = menu.getParentId();
            if (!parentMap.containsKey(parentId)) {
                parentMap.put(parentId, new ArrayList<>());
            }
            parentMap.get(parentId).add(menu);
        }

        // 获取顶级节点
        List<SysMenu> rootMenus = parentMap.get(null);
        if (rootMenus != null) {
            // 递归构建路由
            for (SysMenu rootMenu : rootMenus) {
                Map<String, Object> router = buildRouter(rootMenu, parentMap);
                routers.add(router);
            }
        }

        return routers;
    }

    /**
     * 构建单个路由配置
     */
    private Map<String, Object> buildRouter(SysMenu menu, Map<Integer, List<SysMenu>> parentMap) {
        Map<String, Object> router = new HashMap<>();

        router.put("path", menu.getPath());
        router.put("name", menu.getPath());

        // 处理组件信息
        if ("M".equals(menu.getMenuType())) {
            router.put("component", "Layout");
            // 目录需要重定向到第一个子菜单
            if (menu.getRedirect() != null) {
                router.put("redirect", menu.getRedirect());
            }
        } else {
            router.put("component", menu.getComponent());
        }

        // 处理meta信息
        Map<String, Object> meta = new HashMap<>();
        meta.put("title", menu.getMenuName());
        meta.put("icon", menu.getIcon());
        meta.put("noCache", menu.getIsCache() == 0);
        router.put("meta", meta);

        // 处理子路由
        List<SysMenu> children = parentMap.get(menu.getId());
        if (children != null && !children.isEmpty()) {
            List<Map<String, Object>> childrenRouters = new ArrayList<>();
            for (SysMenu child : children) {
                Map<String, Object> childRouter = buildRouter(child, parentMap);
                childrenRouters.add(childRouter);
            }
            router.put("children", childrenRouters);
        }

        return router;
    }
}
